class Snake{
	constructor(select){
		this.map = document.querySelector(select)
		this.direction="right"
		this.snakelist=[]
		this.createSnake()
		//this.move()
	}
	
	//蛇头	
	creatHead(){
		
		const pos = {x:0,y:0}
			
		const head = this.snakelist[0]
		if(head){
			switch(this.direction){
				case "left":
				pos.x = head.offsetLeft-10
				pos.y = head.offsetTop
				break;
				case "right":
				pos.x = head.offsetLeft+10
				pos.y = head.offsetTop
				break;
				case "top":
				pos.x = head.offsetLeft
				pos.y = head.offsetTop-10
				break;
				case "bottom":
				pos.x = head.offsetLeft
				pos.y = head.offsetTop+10
				break;
				default:
				break;
			}
			head.className="body"
			
		}else{
			
		}
		
		const div = document.createElement("div")
		div.className="head"
		div.value= (pos.x + "px" + pos.y + "px")
		this.snakelist.unshift(div)
		div.style.left = pos.x + "px"
		div.style.top = pos.y + "px"
		
		this.map.appendChild(div)
	}
	
	createSnake(){
		for(let i = 0;i<4;i++){
			this.creatHead();
		}
	}
	
	//让蛇动
	move(){
		//删除蛇头
		const body = this.snakelist.pop()
		body.remove()
		//新增蛇头
		this.creatHead()
	}
	//判断蛇吃食u
	isEat(foodX,foodY){
		const head = this.snakelist[0]
		const headX = head.offsetLeft
		const headY = head.offsetTop
		// if(foodX === headX && foodY === headY ){
		if(Math.abs(foodX - headX)<7 && Math.abs(foodY - headY) <7 ){
			return true
		}
		return false
	}
	
	//判断蛇生死
	isDie(){
		const head = this.snakelist[0]
		const headX = head.offsetLeft
		const headY = head.offsetTop
		for (var i=1;i<this.snakelist.length;i++){
			if(this.snakelist[i].value == (headX + "px" + headY + "px")){
				alert("Game Over")
				return true
			}
		}
		// if(headX < 0 || headY < 0 || headX == 200 || headY == 200 ){
		// 	alert("你竟然吃墙！")
		// 	return true
		// }
		return false
	}
	isBaller(){
		const head = this.snakelist[0]
		const headX = head.offsetLeft
		const headY = head.offsetTop
		
		if(headX<0){
			head.style.left=this.map.clientWidth-10+"px"
		}else if(headX>this.map.clientWidth){
			head.style.left=0+"px"
		}else if(headY<0){
			head.style.top=this.map.clientHeight-10+"px"
		}else if(headY>this.map.clientHeight){
			head.style.top=0+"px"
		}
	}
	
	
}